<template>
  <div class="app-container">
    <div class="user-info-container" v-if="userData">
      <h2>用户备份恢复</h2>
      <div class="user-info">
        <el-avatar :src="userData.avatar" :size="60"></el-avatar>
        <div class="user-details">
          <h3>{{ userData.nickName || userData.userName }}</h3>
          <p>用户ID: {{ userData.userId }}</p>
        </div>
      </div>
    </div>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>备份列表</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-refresh"
          @click="getBackupList"
        >刷新</el-button>
      </div>
      <el-table v-loading="loading" :data="backupList" style="width: 100%">
        <el-table-column label="备份ID" align="center" prop="backupId" />
        <el-table-column label="备份时间" align="center" prop="backupTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.backupTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="文件数量" align="center" prop="fileCount" />
        <el-table-column label="备份大小" align="center" prop="backupSize">
          <template slot-scope="scope">
            <span>{{ storageUnitFormat(scope.row.backupSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="viewBackupFiles(scope.row)"
            >查看文件</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 备份文件列表对话框 -->
    <el-dialog :title="'备份文件列表'" :visible.sync="fileListDialogVisible" width="800px">
      <el-table v-loading="filesLoading" :data="backupFileList" style="width: 100%">
        <el-table-column type="selection" width="55" align="center" @selection-change="handleFileSelectionChange" />
        <el-table-column label="文件名" align="left" prop="fileName" show-overflow-tooltip />
        <el-table-column label="文件路径" align="left" prop="filePath" show-overflow-tooltip />
        <el-table-column label="文件大小" align="center" prop="fileSize">
          <template slot-scope="scope">
            <span>{{ storageUnitFormat(scope.row.fileSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备份时间" align="center" prop="backupTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.backupTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="restoreSelectedFiles" :disabled="selectedFiles.length === 0">恢复选中文件</el-button>
        <el-button @click="fileListDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listUserBackups, restoreFiles, getBackupFiles } from "@/api/disk/storage";
import { getUserProfileById } from "@/api/system/user";

export default {
  name: "Restore",
  data() {
    return {
      // 遮罩层
      loading: true,
      filesLoading: false,
      userId: null,
      userData: null,
      backupList: [],
      currentBackup: null,
      fileListDialogVisible: false,
      backupFileList: [],
      selectedFiles: []
    };
  },
  created() {
    this.userId = this.$route.query.userId;
    if (this.userId) {
      this.getUserData();
      this.getBackupList();
      // 显示开发提示
      this.$notify({
        title: '开发提示',
        message: '备份恢复功能需要后端API支持，请确保后端已实现相应接口：/disk/storage/backup, /disk/storage/backups, /disk/storage/restore',
        type: 'warning',
        duration: 0
      });
    } else {
      this.$message.error("未提供用户ID，无法获取备份信息");
    }
  },
  methods: {
    /** 获取用户信息 */
    getUserData() {
      getUserProfileById(this.userId).then(response => {
        this.userData = response.data;
      });
    },
    /** 获取用户备份列表 */
    getBackupList() {
      this.loading = true;
      listUserBackups(this.userId).then(response => {
        this.backupList = response.data;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        if (error && error.response && error.response.status === 404) {
          this.$message.error("备份列表API未实现，请联系系统管理员");
          // 提供模拟数据以便测试UI
          this.backupList = [
            {
              backupId: "mock-backup-1",
              backupTime: new Date().getTime() - 86400000,
              fileCount: 10,
              backupSize: 1024 * 1024 * 50
            }
          ];
        } else {
          this.$message.error("获取备份列表失败，请重试");
        }
      });
    },
    /** 查看备份中的文件列表 */
    viewBackupFiles(backup) {
      this.currentBackup = backup;
      this.filesLoading = true;
      this.fileListDialogVisible = true;
      
      getBackupFiles(this.userId, backup.backupId).then(response => {
        this.backupFileList = response.data || [];
        this.filesLoading = false;
      }).catch(error => {
        this.filesLoading = false;
        if (error && error.response && error.response.status === 404) {
          this.$message.error("备份文件列表API未实现，请联系系统管理员");
          // 提供模拟数据以便测试UI
          this.backupFileList = [
            {
              fileId: "mock-file-1",
              fileName: "示例文档.docx",
              filePath: "/文档/示例文档.docx",
              fileSize: 1024 * 1024 * 2,
              backupTime: new Date().getTime() - 86400000
            },
            {
              fileId: "mock-file-2",
              fileName: "测试图片.jpg",
              filePath: "/图片/测试图片.jpg",
              fileSize: 1024 * 1024 * 5,
              backupTime: new Date().getTime() - 86400000
            }
          ];
        } else {
          this.$message.error("获取备份文件列表失败，请重试");
        }
      });
    },
    /** 文件多选框选择 */
    handleFileSelectionChange(selection) {
      this.selectedFiles = selection;
    },
    /** 恢复选中的文件 */
    restoreSelectedFiles() {
      const fileIds = this.selectedFiles.map(file => file.fileId);
      this.$modal.confirm('确认要恢复选中的' + fileIds.length + '个文件吗？').then(() => {
        const data = {
          userId: this.userId,
          backupId: this.currentBackup.backupId,
          fileIds: fileIds
        };
        restoreFiles(data).then(response => {
          this.$modal.msgSuccess("文件恢复成功");
          this.fileListDialogVisible = false;
        }).catch(error => {
          if (error && error.response && error.response.status === 404) {
            this.$modal.msgError("文件恢复API未实现，请联系系统管理员");
          } else {
            this.$modal.msgError("文件恢复失败，请重试");
          }
        });
      }).catch(() => {});
    },
    /** 格式化存储容量显示 */
    storageUnitFormat(value) {
      if (value === null || value === undefined) return "0 B";
      
      const units = ['B', 'KB', 'MB', 'GB', 'TB'];
      let size = parseFloat(value);
      let unitIndex = 0;
      
      while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
      }
      
      return size.toFixed(2) + ' ' + units[unitIndex];
    }
  }
};
</script>

<style scoped>
.user-info-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.user-info {
  display: flex;
  align-items: center;
  margin-top: 15px;
}
.user-details {
  margin-left: 15px;
}
.user-details h3 {
  margin: 0 0 5px 0;
}
.user-details p {
  margin: 0;
  color: #606266;
}
</style> 